package cn.hchaojie.camp.day07;

import org.junit.Test;

public class DemoSubString {
	@Test
	public void test() {
		String s = "hello world";
//		System.out.println(s.substring(6));	// 取子串
		
		String sub = "world";
//		System.out.println(s.indexOf(sub));
		
		System.out.println(indexOf(s, sub));
		System.out.println(indexOf(s, "hello"));
		System.out.println(indexOf(s, "ll"));
		System.out.println(indexOf("", "java"));
	}
	
	@Test
	public void testLastWorld() {
		
		System.out.println(lastWorld("hello world"));
		System.out.println(lastWorld("world d"));
		System.out.println(lastWorld("world java     "));
		
		System.out.println(lastWorld("hello"));
		// System.out.println(lastWorld("    "));
		System.out.println(lastWorld(""));
	}
	
	public int lastWorld(String str) {
		int i = str.length() - 1;
		while (i >= 0 && str.charAt(i) == ' ') {
			i--;
		}
		
		for (; i >= 0; i--) {
			char c = str.charAt(i);
			
			if (c == ' ') {
				return i + 1;
			}
		}
		
		if (i == -1) {
			return 0;
		}
		
		return -1;
	}

	public int indexOf(String str, String sub) {
		for (int i = 0; i < str.length(); i++) {

			for (int j = 0; j < sub.length() && (i + j) < str.length(); j++) {
				char c1 = str.charAt(i + j);
				char c2 = sub.charAt(j);
				
				if (c1 != c2) {
					break;
				}
				
				// 如果比较到最后一个
				if (j == sub.length() - 1) {
					return i;
				}
			}
		}
		
		
		return -1;
	}
	
}
